package edu.hawaii.ics466.views;

import java.util.concurrent.TimeUnit;

import edu.hawaii.ics466.R;
import edu.hawaii.ics466.tasks.AddReview;
import android.app.Dialog;
import android.content.Context;
import android.util.Log;
import android.view.DragEvent;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

public class ReviewDialog extends Dialog {

	private String gameName;
	private SeekBar ratingBar;
	private TextView ratingText;
	private TextView reviewBody;

	public ReviewDialog(Context context, final String gameName) {
		super(context);

		setContentView(R.layout.review_dialog);
		setTitle("Rate & Review");

		this.gameName = gameName;
		ratingBar = (SeekBar) findViewById(R.id.rating_bar);
		ratingText = (TextView) findViewById(R.id.rating_text);
		ratingText.setText("Not yet rated.");
		reviewBody = (TextView) findViewById(R.id.review_body);

		ratingBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

			private final String[] ratings = { "Not yet rated.", "1 - Failure", "2 - Poor", "3 - Decent", "4 - Good",
					"5 - Awesome" };

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
			}

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
				ratingText.setText(ratings[progress]);
			}
		});

		Button okButton = (Button) findViewById(R.id.ok_rate_button);
		okButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				ReviewDialog.this.addReview();
			}
		});

		Button cancelButton = (Button) findViewById(R.id.cancel_rate_button);
		cancelButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				ReviewDialog.this.cancel();				
			}
		});
	}

	public void addReview() {
		String body = ((TextView) findViewById(R.id.review_body)).getText().toString();
		String rating = Integer.toString(((SeekBar) findViewById(R.id.rating_bar)).getProgress());
		if (body.isEmpty() || rating.equals("0")) {
			return;
		}
		Boolean success = false;
		String[] requestParams = { gameName, "user", body, rating };
		try {
			success = new AddReview().execute(requestParams).get(3, TimeUnit.SECONDS);
		} catch (Exception e) {

		}
		if (success == null) {
			Toast.makeText(ReviewDialog.this.getContext(), "Failed to make review. Ajax error.", Toast.LENGTH_SHORT)
					.show();
		} else if (!success) {
			Toast.makeText(ReviewDialog.this.getContext(), "Failed to make review. SQL error.", Toast.LENGTH_SHORT)
					.show();
		} else {
			ReviewDialog.this.dismiss();
		}
	}
}
